# !/usr/bin/env python
# -*-coding:utf-8 -*-
"""
# File       : jwt_utils.py
# Time       ：2023/7/9 16:45
# Author     ：Y-aong
# version    ：python 3.7
# Description：
    jwt工具类
    jwt utils
"""
import hashlib
from datetime import datetime, timedelta

import jwt
from jwt import ExpiredSignatureError, DecodeError

from conf.config import FlaskConfig
from public.api_exceptions.api_exceptions import JWTVerifyException


def encrypt_password(value: str) -> str:
    hash_lib = hashlib.md5()
    hash_lib.update(value.encode(encoding='utf8'))
    return hash_lib.hexdigest()


class JWTUtils:
    def __init__(self):
        self.expiry = FlaskConfig.EXPIRY
        self.secret_key = FlaskConfig.SECRET_KEY

    def generate_token(self, payload: dict, expiry: int, secret=None) -> str:
        payload['exp'] = datetime.utcnow() + timedelta(seconds=expiry)
        if not secret:
            secret = self.secret_key
        return jwt.encode(payload, secret, algorithm="HS256")

    def verify_token(self, token, secret=None) -> dict:
        if not secret:
            secret = self.secret_key
        try:
            payload = jwt.decode(token, secret, algorithms=["HS256"])
        except ExpiredSignatureError:
            raise JWTVerifyException("The current token has expired.")
        except DecodeError:
            raise DecodeError("jwt parse failed.")

        return payload

    def refresh_token(self, token: str, secret=None):
        payload = self.verify_token(token, secret)
        return self.generate_token(payload, expiry=self.expiry)
